package com.ketayao.action.admin;

import java.sql.Timestamp;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ketayao.fensy.mvc.RequestContext;
import com.ketayao.pojo.Album;
import com.ketayao.pojo.Picture;
import com.ketayao.system.Constants;

public class PictureAction {

	private static final String CREATE = "admin/album/picture-create";
	private static final String READ = "admin/album/picture-read";
	private static final String VIEW = "admin/album/picture-view";
	
	public String read(RequestContext rc) {
		List<Album> albums =  (List<Album>) Album.INSTANCE.list();
		 rc.getRequest().setAttribute("albums", albums);
		return READ;
	}
	
	public String view(RequestContext rc, String[] args) {
		List<Picture> list = (List<Picture>) Picture.INSTANCE.list("albumId = " + NumberUtils.toLong(args[0]) + " order by priority asc");
		rc.getRequest().setAttribute("pictures", list);
		return VIEW;
	}
	
	public String delete(RequestContext rc, String[] args) throws Exception {
		Picture picture = new Picture();
		picture.setId(NumberUtils.toLong(args[1]));
		picture.delete();
			
		return view(rc,args);
	}
	
	public String preCreate(RequestContext rc) {
		 List<Album> albums =  (List<Album>) Album.INSTANCE.list();
		 rc.getRequest().setAttribute("albums", albums);
		return CREATE;
	}
	
	public String create(RequestContext rc){
		long albumId = rc.getParam("albumId",0L);
		String pictureInfo = rc.getParam("pictureInfo");
		if(albumId != 0 && StringUtils.isNotBlank(pictureInfo)){
			JSONArray array = JSONArray.parseArray(pictureInfo);
			if(array != null && array.size() > 0){
				Picture picture = new Picture();
				picture.setAlbumId(albumId);
				String contextPath = rc.getContextPath();
				for(int i=0 ; i < array.size() ; i++){
					JSONObject obj = array.getJSONObject(i);
					if(obj.containsKey("path")){
						String currPath = obj.getString("path");
						if(contextPath.length() > 1 && currPath.contains(contextPath)){
							currPath = currPath.substring(currPath.indexOf(contextPath)+contextPath.length());
						}
						picture.setPath(currPath);
					}
					if(obj.containsKey("title")){
						picture.setTitle(obj.getString("title"));
					}
					if(obj.containsKey("priority")){
						picture.setPriority(obj.getInteger("priority"));
					}
					if(obj.containsKey("description")){
						picture.setDescription(obj.getString("description"));
					}
					
					picture.setCreateTime(new Timestamp(System.currentTimeMillis()));
					picture.save();
				}
				
				rc.setRequestAttr(Constants.OPERATION_SUCCESS, Constants.OPERATION_SUCCESS);
			}
		}
		return preCreate(rc);
	}
}
